import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:file_picker/file_picker.dart';
import '../../../data/models/project_model.dart';

/// Excel上传组件
/// 支持文件选择、上传进度显示、错误处理
class ExcelUploadWidget extends ConsumerStatefulWidget {
  final ProjectModel project;
  final VoidCallback? onUploadSuccess;
  final Function(String)? onUploadError;

  const ExcelUploadWidget({
    super.key,
    required this.project,
    this.onUploadSuccess,
    this.onUploadError,
  });

  @override
  ConsumerState<ExcelUploadWidget> createState() => _ExcelUploadWidgetState();
}

class _ExcelUploadWidgetState extends ConsumerState<ExcelUploadWidget> {
  PlatformFile? _selectedFile;
  bool _isUploading = false;
  double _uploadProgress = 0.0;
  String? _uploadError;
  final TextEditingController _demanderController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();

  @override
  void dispose() {
    _demanderController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  /// 选择Excel文件
  Future<void> _selectFile() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['xlsx', 'xls'],
        allowMultiple: false,
      );

      if (result != null) {
        PlatformFile file = result.files.first;

        // 文件大小检查 (限制20MB)
        if (file.size > 20 * 1024 * 1024) {
          setState(() {
            _uploadError = '文件大小超过20MB限制，请选择较小的文件';
          });
          return;
        }

        setState(() {
          _selectedFile = file;
          _uploadError = null;
        });
      }
    } catch (e) {
      setState(() {
        _uploadError = '文件选择失败: ${e.toString()}';
      });
    }
  }

  /// 上传Excel文件
  Future<void> _uploadFile() async {
    if (_selectedFile == null) {
      setState(() {
        _uploadError = '请先选择Excel文件';
      });
      return;
    }

    setState(() {
      _isUploading = true;
      _uploadProgress = 0.0;
      _uploadError = null;
    });

    try {
      // 模拟上传进度
      for (int i = 0; i <= 100; i += 10) {
        await Future.delayed(const Duration(milliseconds: 100));
        setState(() {
          _uploadProgress = i / 100.0;
        });
      }

      // 调用实际的上传API
      // final excelProvider = ref.read(excelProviderProvider.notifier);
      // await excelProvider.uploadExcel(
      //   file: _selectedFile!,
      //   projectId: widget.project.id,
      //   demander: _demanderController.text,
      //   description: _descriptionController.text,
      // );

      setState(() {
        _isUploading = false;
        _uploadProgress = 1.0;
      });

      // 上传成功回调
      if (widget.onUploadSuccess != null) {
        widget.onUploadSuccess!();
      }

      // 显示成功消息
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Excel文件上传成功'),
            backgroundColor: Colors.green,
          ),
        );
      }

      // 重置状态
      _resetUploadState();
    } catch (e) {
      setState(() {
        _isUploading = false;
        _uploadError = '上传失败: ${e.toString()}';
      });

      if (widget.onUploadError != null) {
        widget.onUploadError!(_uploadError!);
      }
    }
  }

  /// 重置上传状态
  void _resetUploadState() {
    setState(() {
      _selectedFile = null;
      _uploadProgress = 0.0;
      _uploadError = null;
    });
    _demanderController.clear();
    _descriptionController.clear();
  }

  /// 获取文件大小显示文本
  String _getFileSizeText(int bytes) {
    if (bytes < 1024) {
      return '${bytes}B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)}KB';
    } else {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)}MB';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.all(16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题
            Row(
              children: [
                const Icon(Icons.file_upload, color: Colors.blue),
                const SizedBox(width: 8),
                Text(
                  'Excel文件上传',
                  style: Theme.of(context).textTheme.titleLarge,
                ),
              ],
            ),
            const SizedBox(height: 16),

            // 项目信息
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: [
                  const Icon(Icons.folder, color: Colors.blue),
                  const SizedBox(width: 8),
                  Text(
                    '项目: ${widget.project.projectName}',
                    style: const TextStyle(fontWeight: FontWeight.w500),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),

            // 文件选择区域
            GestureDetector(
              onTap: _isUploading ? null : _selectFile,
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.all(24),
                decoration: BoxDecoration(
                  border: Border.all(
                    color: _selectedFile != null
                        ? Colors.green
                        : Colors.grey.shade300,
                    width: 2,
                  ),
                  borderRadius: BorderRadius.circular(12),
                  color: _selectedFile != null
                      ? Colors.green.shade50
                      : Colors.grey.shade50,
                ),
                child: Column(
                  children: [
                    Icon(
                      _selectedFile != null
                          ? Icons.check_circle
                          : Icons.cloud_upload,
                      size: 48,
                      color: _selectedFile != null ? Colors.green : Colors.grey,
                    ),
                    const SizedBox(height: 12),
                    Text(
                      _selectedFile != null
                          ? _selectedFile!.name
                          : '点击选择Excel文件',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                        color: _selectedFile != null
                            ? Colors.green
                            : Colors.grey.shade600,
                      ),
                    ),
                    if (_selectedFile != null) ...[
                      const SizedBox(height: 4),
                      Text(
                        _getFileSizeText(_selectedFile!.size),
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey.shade600,
                        ),
                      ),
                    ],
                    const SizedBox(height: 8),
                    Text(
                      '支持 .xlsx, .xls 格式，最大20MB',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey.shade500,
                      ),
                    ),
                  ],
                ),
              ),
            ),

            if (_selectedFile != null) ...[
              const SizedBox(height: 16),

              // 需求提供方输入
              TextField(
                controller: _demanderController,
                decoration: const InputDecoration(
                  labelText: '需求提供方',
                  hintText: '请输入需求提供方名称',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.person),
                ),
                enabled: !_isUploading,
              ),
              const SizedBox(height: 16),

              // 描述输入
              TextField(
                controller: _descriptionController,
                decoration: const InputDecoration(
                  labelText: '描述',
                  hintText: '请输入Excel文件描述（可选）',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.description),
                ),
                maxLines: 3,
                enabled: !_isUploading,
              ),
            ],

            // 上传进度
            if (_isUploading) ...[
              const SizedBox(height: 16),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '上传进度: ${(_uploadProgress * 100).toInt()}%',
                    style: const TextStyle(fontWeight: FontWeight.w500),
                  ),
                  const SizedBox(height: 8),
                  LinearProgressIndicator(
                    value: _uploadProgress,
                    backgroundColor: Colors.grey.shade300,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                  ),
                ],
              ),
            ],

            // 错误信息
            if (_uploadError != null) ...[
              const SizedBox(height: 16),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.red.shade50,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.red.shade200),
                ),
                child: Row(
                  children: [
                    const Icon(Icons.error, color: Colors.red),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        _uploadError!,
                        style: const TextStyle(color: Colors.red),
                      ),
                    ),
                  ],
                ),
              ),
            ],

            // 操作按钮
            const SizedBox(height: 24),
            Row(
              children: [
                if (_selectedFile != null && !_isUploading) ...[
                  TextButton(
                    onPressed: _resetUploadState,
                    child: const SelectableText('重新选择'),
                  ),
                  const SizedBox(width: 16),
                ],
                Expanded(
                  child: ElevatedButton(
                    onPressed: _selectedFile != null && !_isUploading
                        ? _uploadFile
                        : null,
                    child: _isUploading
                        ? const Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              SizedBox(
                                width: 16,
                                height: 16,
                                child:
                                    CircularProgressIndicator(strokeWidth: 2),
                              ),
                              SizedBox(width: 8),
                              SelectableText('上传中...'),
                            ],
                          )
                        : const SelectableText('上传文件'),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            // 添加链接到智能电子表格的按钮
            Center(
              child: TextButton(
                onPressed: () {
                  // 导航到智能电子表格页面
                  Navigator.of(context).pushNamed('/spreadsheet');
                },
                child: const SelectableText('或使用智能电子表格连接数据库'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
